package cn.itcast.user.filter;

import cn.itcast.hmall.dto.common.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author oldwine
 * @date 2022/6/21
 * @Version 1.0
 */

@Component
public class UserIdInterceptor extends HandlerInterceptorAdapter {

    /**
     * 前置拦截: 获取请求头中的userId,如放入当前线程中
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头信息
        String header = request.getHeader("authorization");

        if (!StringUtils.isEmpty(header)) {
            //2.存入线程中
            ThreadLocalUtil.setUserId(Long.valueOf(header));
        }
        return super.preHandle(request, response, handler);
    }

    /**
     * 清理线程中的数据
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ThreadLocalUtil.clear();
        super.postHandle(request, response, handler, modelAndView);
    }

}

